import redis

REDIS_CLIENT_VERSION = redis.__version__
IS_REDIS_VERSION2 = REDIS_CLIENT_VERSION.startswith('2.')

REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
REDIS_PASSWD = None
REDIS_DB = 1

REDIS_KEY = "try:zset"

class RedisOrderdSetClient(object):

    def __init__(self, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWD, db=REDIS_DB):
        self.db = redis.StrictRedis(host=host, port=port, password=password, db=db, decode_responses=True)

    def add(self, strFoo, sore) -> int:
        if not self.exist(strFoo):
            if IS_REDIS_VERSION2:
                return self.db.zadd(REDIS_KEY, sore, strFoo)
            else :
                return self.db.zadd(REDIS_KEY, {strFoo: sore})

    def get(self, strFoo) -> int:
        return self.db.zscore(REDIS_KEY, strFoo)

    def exist(self, strFoo) -> bool:
        return not self.db.zscore(REDIS_KEY, strFoo) is None

    def count(self) -> int:
        return self.db.zcard(REDIS_KEY)

    def increase(self, strFoo, amount):
        if IS_REDIS_VERSION2:
            self.db.zincrby(REDIS_KEY, strFoo, amount)
        else :
            self.db.zincrby(REDIS_KEY, amount, strFoo);
    
    def get_range_by_sore(self, min_sore, max_sore):
        return self.db.zrangebyscore(REDIS_KEY, min_sore, max_sore)

    def batch(self, cursor, count):
        cursor, data = self.db.zscan(REDIS_KEY, cursor=cursor, count=count)
        print(f"cursor {cursor}")
        return data

    def remove(self, strFoo):
        self.db.zrem(REDIS_KEY, strFoo)

if __name__ == '__main__':
    conn = RedisOrderdSetClient()
    print(conn.add("Apple", 20))
    print(conn.add("Apple", 20))
    print(conn.get("Apple"))
    print(conn.get("Apple"))
    print(conn.count())
    conn.increase("Pear", 1)
    print(conn.count())
    print(conn.get("Pear"))
    conn.increase("Apple", -1)
    print(conn.get("Pear"))
    print(conn.get("Apple"))
    
    print(conn.add("pipper", 1001))
    print(conn.add("tomato", 1002))
    print(conn.add("potato", 1005))
    for item in conn.get_range_by_sore(1000, 2000):
        print(item)

    print(conn.count())
    print(conn.add("cat", 2001))
    print(conn.add("dog", 2002))
    print(conn.add("tigger", 2003))
    print(conn.add("lion", 2004))
    print(conn.add("bufflo", 2005))
    print(conn.add("mouse", 2006))
    print(conn.add("chicken", 2007))
    print(conn.add("duck", 2008))
    print(conn.add("wolf", 2009))
    data = conn.batch(0, 2)
    for item in data:
        print(f"item {item[0]}")
        conn.remove(item[0])
    
    print(conn.count())
